package com.senven.myapplication;

import android.app.Application;
import android.os.AsyncTask;
import android.util.Log;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class MyViewModel extends AndroidViewModel {
    private static final String TAG = "MyViewModel";

    private MutableLiveData<List<String>> data;

    public MyViewModel(Application application){
        super(application);
    }

    public LiveData<List<String>> getData(){
        if (data == null) {
            data = new MutableLiveData<List<String>>();
            loadData();
        }
        return data;
    }

    private void loadData(){
        new AsyncTask<Void, Void, List<String>>(){
            @Override
            protected List<String> doInBackground(Void... voids) {
                ArrayList<String> result = new ArrayList<>(0);

                String myFeed = getApplication().getString(R.string.my_feed);
                try {
                    URL url = new URL(myFeed);
                    URLConnection connection = url.openConnection();
                    HttpURLConnection httpConnection = (HttpURLConnection) connection;
                    int response = httpConnection.getResponseCode();
                    if (response == HttpURLConnection.HTTP_OK){
                        InputStream in = httpConnection.getInputStream();
                        // 处理输入流以生成结果列表
                        result = processStream(in);
                    }
                    httpConnection.disconnect();
                } catch (MalformedURLException e){
                    Log.e(TAG, "Malformed URL Exception.", e);
                } catch (IOException e) {
                    Log.e(TAG, "IO Exception.", e);
                }
                return result;
            }

            private ArrayList<String> processStream(InputStream in){
                return  null;
            }

            @Override
            protected void onPostExecute(List<String> strings) {
                data.setValue(strings);
            }
        }.execute();
    }
}
